package com.kexio.security.domain;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kexio.core.data.domain.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.time.LocalDateTime;

/**
 * 用户角色关联实体
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_user_role")
@Schema(description = "用户角色关联实体")
public class UserRole extends BaseEntity {

    /**
     * 用户ID
     */
    @NotNull(message = "用户ID不能为空")
    @TableField("user_id")
    @Schema(description = "用户ID", example = "1")
    private Long userId;

    /**
     * 角色ID
     */
    @NotNull(message = "角色ID不能为空")
    @TableField("role_id")
    @Schema(description = "角色ID", example = "1")
    private Long roleId;

    /**
     * 是否通过继承获得（如：部门角色、岗位角色）
     */
    @TableField("is_inherited")
    @Schema(description = "是否通过继承获得", example = "false")
    private Boolean isInherited = false;

    /**
     * 生效时间
     */
    @TableField("start_time")
    @Schema(description = "生效时间", example = "2024-01-01 00:00:00")
    private LocalDateTime startTime;

    /**
     * 失效时间
     */
    @TableField("end_time")
    @Schema(description = "失效时间", example = "2024-12-31 23:59:59")
    private LocalDateTime endTime;

    /**
     * 租户ID
     */
    @TableField("tenant_id")
    @Schema(description = "租户ID", example = "1")
    private Long tenantId;

    // =========================== 便利方法 ===========================

    /**
     * 检查关联关系是否有效
     * @return 是否有效
     */
    public boolean isValid() {
        LocalDateTime now = LocalDateTime.now();
        return (startTime == null || !now.isBefore(startTime)) 
            && (endTime == null || !now.isAfter(endTime));
    }

    /**
     * 检查关联关系是否已过期
     * @return 是否已过期
     */
    public boolean isExpired() {
        if (endTime == null) {
            return false;
        }
        return LocalDateTime.now().isAfter(endTime);
    }

    /**
     * 检查关联关系是否还未生效
     * @return 是否还未生效
     */
    public boolean isPending() {
        if (startTime == null) {
            return false;
        }
        return LocalDateTime.now().isBefore(startTime);
    }

    /**
     * 设置永久有效的关联关系
     */
    public void setPermanent() {
        this.startTime = null;
        this.endTime = null;
    }

    /**
     * 设置临时关联关系
     * @param startTime 开始时间
     * @param endTime 结束时间
     */
    public void setTemporary(LocalDateTime startTime, LocalDateTime endTime) {
        this.startTime = startTime;
        this.endTime = endTime;
    }
}
